package com.gaoyi.basemodule.baseUtil;

import android.app.Activity;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.gaoyi.basemodule.baseconstant.SPName;

import java.util.ArrayList;
import java.util.List;

public class ActivityUtil {
    private final List<Activity> activityList;

    private static volatile ActivityUtil instance;

    public ActivityUtil() {
        activityList = new ArrayList<>();
    }

    public static ActivityUtil getInstance() {
        if (instance == null) {
            synchronized (ActivityUtil.class) {
                if (instance == null) {
                    instance = new ActivityUtil();
                }
            }
        }
        return instance;
    }

    public void addActivity(Activity activity) {
        if (!activityList.contains(activity)) {
            activityList.add(activity);
        }
    }

    public void removeActivity(Activity activity) {
        if (activityList != null && !activityList.isEmpty()) {
            activityList.remove(activity);
            activity = null;
        }
    }

    public void removeAllActivity() {
        if (activityList != null && !activityList.isEmpty()) {
            for (Activity activity : activityList) {
                activity.finish();
                activity = null;
            }
            activityList.clear();
        }
    }

    public boolean isSurvive(Activity activity) {
        return activity != null && !activity.isFinishing() && !activity.isDestroyed();
    }

    public void removeChildFragment(Fragment fragment) {
        if (fragment == null) {
            return;
        }
        FragmentManager fm = fragment.getChildFragmentManager();
        removeFragment(fm);
    }

    public void removeFragment(FragmentActivity activity) {
        if (activity == null) {
            return;
        }
        FragmentManager fm = activity.getSupportFragmentManager();
        removeFragment(fm);
    }

    private void removeFragment(FragmentManager fm) {
        List<Fragment> fragments = fm.getFragments();
        if (!fragments.isEmpty()) {
            FragmentTransaction transaction = fm.beginTransaction();
            for (Fragment fragment : fragments) {
                transaction.remove(fragment);
            }
            transaction.commitAllowingStateLoss();
        }
    }

    public void logout() {
        SPUtil.getInstance().putString(SPName.TOKEN, "");
        SPUtil.getInstance().putString(SPName.REFRESH_TOKEN, "");
        SPUtil.getInstance().putString(SPName.ID, "");
        SPUtil.getInstance().putInt(SPName.LANGUAGE, LanguageUtils.LANG_CHINA);
        removeAllActivity();
    }
}
